package com.leonwoodstudio.endorsementclient;

import android.content.Context;
import android.os.AsyncTask;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

/**
 * Created by win7 on 2017/3/15.
 */
public class ParseXmlAsyncTask extends AsyncTask<String, Void, Void> {
    Context context;
    boolean success;
    String plate_num;
    String event_type;

    public ParseXmlAsyncTask(Context context) {
        super();
        this.context = context;
        success = false;
    }

    protected Void doInBackground(String... file) {
        parseXml(file[0]);
        return null;
    }

    protected void onPostExecute(Void result) {
        MainActivity activity = (MainActivity)context;
        if (success) {
            activity.status_message.setText("车牌号: " + plate_num + "\n违法类型: " + event_type);
        } else {
            activity.status_message.setText("解析XML文件失败!");
        }
    }

    void parseXml(String file) {
        try {
            FileInputStream fis = new FileInputStream(file);
//            BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
//            String temp = null;
//            StringBuffer sb = new StringBuffer();
//            while ((temp = br.readLine()) != null) {
//                sb.append(temp + "\n");
//            }
//            System.out.println(sb.toString());
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//创建DOM解析工厂
            DocumentBuilder dom_build = factory.newDocumentBuilder();//创建DON解析器
            Document dom = dom_build.parse(fis);//开始解析XML文档并且得到整个文档的对象模型
            Element root= dom.getDocumentElement();//得到根节点<wfdataContent>
            NodeList nodes = root.getChildNodes();
            for (int i = 0; i < nodes.getLength(); i++) {
                if ("PlateNum".equals(nodes.item(i).getNodeName())) {
                    plate_num = nodes.item(i).getTextContent();
                } else if ("EventType".equals(nodes.item(i).getNodeName())) {
                    event_type = nodes.item(i).getTextContent();
                }
            }
            if (plate_num != null && event_type != null) {
                success = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }
}